package com.yndsoft.jc;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yndsoft.jc.activity.BaseFragmentActivity;
import com.yndsoft.jc.fragment.CartFragment;
import com.yndsoft.jc.fragment.CategoryFragment;
import com.yndsoft.jc.fragment.IndexFragment;
import com.yndsoft.jc.fragment.MemberFragment;
import com.yndsoft.jc.utils.DialogHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class MainActivity extends BaseFragmentActivity implements View.OnClickListener {
    private RelativeLayout layout_main_header;
    private static final String CURR_INDEX = "currIndex";
    private static int currIndex = 0;
    private ArrayList<String> fragmentTags;
    private FragmentManager fragmentManager;
    // 定义布局对象
    private FrameLayout layout_main_footer_index, layout_main_footer_category, layout_main_footer_cart, layout_main_footer_member;
    // 定义图片组件对象
    private ImageView layout_main_footer_index_img, layout_main_footer_category_img, layout_main_footer_cart_img, layout_main_footer_member_img;
    // 定义文字组件对象
    private TextView layout_main_footer_index_txt, layout_main_footer_category_txt, layout_main_footer_cart_txt, layout_main_footer_member_txt;
    // 定义按钮图片组件
    private ImageView layout_main_footer_add_btn_img, layout_main_footer_add_btn_img_delete;
    // 定义PopupWindow
    private PopupWindow layout_main_footer_popwindow;
    //再按一次退出程序
    private long exitTime = 0;
    //别名（alias），设置标签（tag）
    //alias 应唯一， tag 即分组，没有唯一性
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;
    //header
    public TextView layout_header_textview;
    public Button layout_header_btn_forward, layout_header_btn_new_friend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        fragmentManager = getSupportFragmentManager();
        fragmentTags = new ArrayList<>(Arrays.asList("IndexFragment", "CategoryFragment", "CartFragment", "MemberFragment"));
        currIndex = 0;
        if (savedInstanceState != null) {
            currIndex = savedInstanceState.getInt(CURR_INDEX);
            hideSavedFragment();
        }
        clickIndex();
        //极光推送
        //setTag("s");
        //setAlias("xiaoyao");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(CURR_INDEX, currIndex);
    }

    private void hideSavedFragment() {
        Fragment fragment = fragmentManager.findFragmentByTag(fragmentTags.get(currIndex));
        if (fragment != null) {
            fragmentManager.beginTransaction().hide(fragment).commit();
        }
    }

    private void initView() {
//        layout_main_header = (RelativeLayout) findViewById(R.id.layout_main_header);
        layout_header_textview = (TextView) findViewById(R.id.layout_header_textview);
        layout_header_btn_forward = (Button) findViewById(R.id.layout_header_btn_forward);
        layout_header_btn_new_friend = (Button) findViewById(R.id.layout_header_btn_new_friend);
        // 实例化布局对象
        layout_main_footer_index = (FrameLayout) findViewById(R.id.layout_main_footer_index);
        layout_main_footer_category = (FrameLayout) findViewById(R.id.layout_main_footer_category);
        layout_main_footer_cart = (FrameLayout) findViewById(R.id.layout_main_footer_cart);
        layout_main_footer_member = (FrameLayout) findViewById(R.id.layout_main_footer_member);
        // 实例化图片组件对象
        layout_main_footer_index_img = (ImageView) findViewById(R.id.layout_main_footer_index_img);
        layout_main_footer_category_img = (ImageView) findViewById(R.id.layout_main_footer_category_img);
        layout_main_footer_cart_img = (ImageView) findViewById(R.id.layout_main_footer_cart_img);
        layout_main_footer_member_img = (ImageView) findViewById(R.id.layout_main_footer_member_img);
        // 实例化文字组件对象
        layout_main_footer_index_txt = (TextView) findViewById(R.id.layout_main_footer_index_txt);
        layout_main_footer_category_txt = (TextView) findViewById(R.id.layout_main_footer_category_txt);
        layout_main_footer_cart_txt = (TextView) findViewById(R.id.layout_main_footer_cart_txt);
        layout_main_footer_member_txt = (TextView) findViewById(R.id.layout_main_footer_member_txt);
        // 实例化按钮图片组件
//        layout_main_footer_add_btn_img = (ImageView) findViewById(R.id.layout_main_footer_add_btn_img);
        // 给布局对象设置监听
        layout_main_footer_index.setOnClickListener(this);
        layout_main_footer_category.setOnClickListener(this);
        layout_main_footer_cart.setOnClickListener(this);
        layout_main_footer_member.setOnClickListener(this);
        // 给按钮图片设置监听
//        layout_main_footer_add_btn_img.setOnClickListener(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //Toast.makeText(MainActivity.this, "MainActivity回调成功！！！requestCode：" + requestCode + ";resultCode:" + resultCode, Toast.LENGTH_SHORT).show();
//        if (requestCode == MemberFragmentCodeEnum.REQUEST_CODE) {
//            switch (resultCode) {
//                case MemberFragmentCodeEnum.RESULT_LOGIN:
//                    break;
//                default:
//                    break;
//            }
//        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_main_footer_index:
                clickIndex();
                break;
            case R.id.layout_main_footer_category:
                clickCategory();
                break;
//            case R.id.layout_main_footer_add_btn_img:
//                clickAdd(v);
//                break;
            case R.id.layout_main_footer_cart:
                clickCart();
                break;
            case R.id.layout_main_footer_member:
                clickMember();
                break;
        }
    }

    private void showFragment() {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag(fragmentTags.get(currIndex));
        if (fragment == null) {
            fragment = instantFragment(currIndex);
        }
        for (int i = 0; i < fragmentTags.size(); i++) {
            Fragment f = fragmentManager.findFragmentByTag(fragmentTags.get(i));
            if (f != null && f.isAdded()) {
                fragmentTransaction.hide(f);
            }
        }
        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(R.id.layout_main_container, fragment, fragmentTags.get(currIndex));
        }
        fragmentTransaction.commitAllowingStateLoss();
        fragmentManager.executePendingTransactions();
    }

    public Fragment instantFragment(int currIndex) {
        switch (currIndex) {
            case 0:
                return new IndexFragment();
            case 1:
                return new CategoryFragment();
            case 2:
                return new CartFragment();
            case 3:
                return new MemberFragment();
            default:
                return null;
        }
    }

    public void clickIndex() {
        //隐藏头部
//        layout_main_header.setVisibility(View.GONE);
//        //layout_header_textview.setText(R.string.main_navigation_menpai);
//        layout_header_btn_new_friend.setVisibility(View.GONE);
        currIndex = 0;
        showFragment();

        layout_main_footer_index_img.setSelected(true);
        layout_main_footer_index_txt.setSelected(true);

        layout_main_footer_category_img.setSelected(false);
        layout_main_footer_category_txt.setSelected(false);

        layout_main_footer_cart_img.setSelected(false);
        layout_main_footer_cart_txt.setSelected(false);

        layout_main_footer_member_txt.setSelected(false);
        layout_main_footer_member_img.setSelected(false);
    }

    public void clickCategory() {
        //显示头部
//        layout_main_header.setVisibility(View.VISIBLE);
//        layout_header_textview.setText(R.string.main_navigation_category);
//        if (CommMethodUtils.isLogin(MainActivity.this) == true) {
//            //layout_header_btn_new_friend.setVisibility(View.VISIBLE);
//        } else {
//            //layout_header_btn_new_friend.setVisibility(View.GONE);
//        }
        currIndex = 1;
        showFragment();

        layout_main_footer_index_img.setSelected(false);
        layout_main_footer_index_txt.setSelected(false);

        layout_main_footer_category_img.setSelected(true);
        layout_main_footer_category_txt.setSelected(true);

        layout_main_footer_cart_img.setSelected(false);
        layout_main_footer_cart_txt.setSelected(false);

        layout_main_footer_member_txt.setSelected(false);
        layout_main_footer_member_img.setSelected(false);
    }

    public void clickCart() {
        //显示头部
//        layout_main_header.setVisibility(View.VISIBLE);
//        layout_header_textview.setText(R.string.main_navigation_cart);
//        layout_header_btn_new_friend.setVisibility(View.GONE);
        currIndex = 2;
        showFragment();

        layout_main_footer_index_img.setSelected(false);
        layout_main_footer_index_txt.setSelected(false);

        layout_main_footer_category_img.setSelected(false);
        layout_main_footer_category_txt.setSelected(false);

        layout_main_footer_cart_img.setSelected(true);
        layout_main_footer_cart_txt.setSelected(true);

        layout_main_footer_member_txt.setSelected(false);
        layout_main_footer_member_img.setSelected(false);
    }

    public void clickMember() {
        //显示头部
//        layout_main_header.setVisibility(View.VISIBLE);
//        layout_header_textview.setText(R.string.main_navigation_member);
//        layout_header_btn_new_friend.setVisibility(View.GONE);
        currIndex = 3;
        showFragment();

        layout_main_footer_index_img.setSelected(false);
        layout_main_footer_index_txt.setSelected(false);

        layout_main_footer_category_img.setSelected(false);
        layout_main_footer_category_txt.setSelected(false);

        layout_main_footer_cart_img.setSelected(false);
        layout_main_footer_cart_txt.setSelected(false);

        layout_main_footer_member_txt.setSelected(true);
        layout_main_footer_member_img.setSelected(true);
    }

    private void clickAdd(View v) {
        //MainPopWindow mainPopWindow = new MainPopWindow(MainActivity.this, v);
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popView = inflater.inflate(R.layout.layout_main_popwindow, null);
        //弹出框里内容
        Button layout_main_footer_popwindow_private = (Button) popView.findViewById(R.id.layout_main_footer_popwindow_private);
        layout_main_footer_popwindow_private.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MainActivity.this, "私下切磋！！！sp_login:" + CommMethodUtils.isLogin(MainActivity.this), Toast.LENGTH_SHORT).show();
                layout_main_footer_popwindow.dismiss();
                Intent intent = new Intent();
//                if (CommMethodUtils.isLogin(MainActivity.this) == true) {
//                    intent.setClass(MainActivity.this, PublishPrivateActivity.class);
//                    startActivity(intent);
//                } else {
//                    intent.setClass(MainActivity.this, LoginActivity.class);
//                    startActivity(intent);
//                    MainActivity.this.finish();
//                }
            }
        });
        // 这里检验popWindow里的button是否可以点击
        ImageButton layout_main_footer_popwindow_close = (ImageButton) popView.findViewById(R.id.layout_main_footer_popwindow_close);
        layout_main_footer_popwindow_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_main_footer_popwindow.dismiss();
            }
        });
        //点击popView非按钮消失
        popView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_main_footer_popwindow.dismiss();
            }
        });
        if (layout_main_footer_popwindow == null) {
            //弹出层居中显示，设置大小
            //int width = getResources().getDisplayMetrics().widthPixels * 3 / 4;
            //int height = getResources().getDisplayMetrics().heightPixels * 3 / 5;
            //layout_main_footer_popwindow = new PopupWindow(view, width, height);
            //获取系统状态栏高度
            Rect frame = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;
            //获取系统的宽度和高度
            int width = getWindow().getDecorView().getWidth();
            int height = getWindow().getDecorView().getHeight() - statusBarHeight;
            //int width = WindowManager.LayoutParams.MATCH_PARENT;
            //int height = WindowManager.LayoutParams.WRAP_CONTENT;
            //Toast.makeText(MainActivity.this, "弹出框......statusBarHeight:" + statusBarHeight + ";height:" + height, Toast.LENGTH_SHORT).show();
            layout_main_footer_popwindow = new PopupWindow(popView, width, height, true);
        }
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        layout_main_footer_popwindow.setFocusable(true);
        // 设置允许在外点击消失
        layout_main_footer_popwindow.setOutsideTouchable(true);
        // 实例化一个ColorDrawable颜色为半透明  0xb0000000
        //ColorDrawable dw = new ColorDrawable(0x30000000);
        //layout_main_footer_popwindow.setBackgroundDrawable(dw);
        // 必须使用该方法
        layout_main_footer_popwindow.setBackgroundDrawable(new BitmapDrawable());
        layout_main_footer_popwindow.setClippingEnabled(false);
        //layout_main_footer_popwindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        // 设置popWindow的显示和消失动画
        layout_main_footer_popwindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        //showAtLocation是作为父布局的一个子布局显示没具体显示位置自己定义，跟父布局无关。
        //showAsDropDown是显示在某个view的旁边，作为同一级布局，具体位置可以根据offset调整。
        layout_main_footer_popwindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        //layout_main_footer_popwindow.showAsDropDown(v, 0, 0);
        //弹出层居中显示  layout_main_footer_popwindow.showAtLocation(v, Gravity.CENTER, 0, 0);
        //popWindow消失监听方法
        layout_main_footer_popwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //Toast.makeText(MainActivity.this, "popWindow消失......", Toast.LENGTH_SHORT).show();
            }
        });
        layout_main_footer_popwindow.update();
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = MainActivity.this.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        MainActivity.this.getWindow().setAttributes(lp);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                DialogHelper.showLongToast(this, "再按一次退出");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置tags
     */
    private void setTag(String tag) {
        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
            Toast.makeText(MainActivity.this, "tag不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!isValidTagAndAlias(sTagItme)) {
                Toast.makeText(MainActivity.this, "格式不对", Toast.LENGTH_SHORT).show();
                return;
            }
            tagSet.add(sTagItme);
        }
        //Toast.makeText(MainActivity.this, "开始调用......", Toast.LENGTH_SHORT).show();
        //调用JPush API设置Tag
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));
    }

    private void setAlias(String alias) {
        if (TextUtils.isEmpty(alias)) {
            Toast.makeText(MainActivity.this, "alias不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (!ExampleUtil.isValidTagAndAlias(alias)) {
//            Toast.makeText(MainActivity.this, "格式不对", Toast.LENGTH_SHORT).show();
//            return;
//        }
        //调用JPush API设置Alias
        //mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, alias));
    }

    // 通过TagAliasCallback的接口回调来判断tag是否与极光推送服务器绑定成功
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            //Toast.makeText(MainActivity.this, "回调成功......", Toast.LENGTH_SHORT).show();
            final String logs;
            switch (code) {
                case 0:
                    logs = "设置别名和标签成功！";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "设置超时，60s后重试！";
                    // 延迟 60 秒来调用 Handler 设置别名
                    if (isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        Toast.makeText(MainActivity.this, "没有连接网络", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    logs = "失败代码 = " + code;
            }
            //ExampleUtil.showToast(logs, getApplicationContext());
        }
    };

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            JPushInterface.setAliasAndTags(getApplicationContext(), "xiaoyao", getSetString("s"), mTagsCallback);
//            switch (msg.what) {
//                case MSG_SET_ALIAS:
//                    Toast.makeText(MainActivity.this, "在handler里面设置alias", Toast.LENGTH_SHORT).show();
//                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mTagsCallback);
//                    break;
//                case MSG_SET_TAGS:
//                    Toast.makeText(MainActivity.this, "在handler里面设置tags", Toast.LENGTH_SHORT).show();
//                    try {
//                        JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
//                    } catch (Exception ex) {
//                        //Toast.makeText(MainActivity.this, "回调出错：" + ex.getMessage() , Toast.LENGTH_SHORT).show();
//                    }
//                    break;
//                default:
//                    break;
//            }
        }
    };

    //JPush
    @Override
    protected void onResume() {
        super.onResume();
        //极光推动统计代码
        JPushInterface.onResume(MainActivity.this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //极光推动统计代码
        JPushInterface.onPause(MainActivity.this);
    }

    // 校验Tag Alias 只能是数字,英文字母和中文
    public boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    public boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    public Set<String> getSetString(String tag) {
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!isValidTagAndAlias(sTagItme)) {
                Toast.makeText(MainActivity.this, "格式不对", Toast.LENGTH_SHORT).show();
                return null;
            }
            tagSet.add(sTagItme);
        }
        return tagSet;
    }
}
